import os
import time
from datetime import datetime
from pathlib import Path

from django.core.files.storage import FileSystemStorage
from django.http import JsonResponse

from L_API import settings
from L_API.settings import img_address, local_ip


def input_img(request):
    file = request.FILES.get('file')
    if file:
        # 生成文件夹路径
        folder_path = os.path.join(settings.MEDIA_ROOT, datetime.now().strftime('%Y/%m/%d'))
        if not os.path.exists(folder_path):
            os.makedirs(folder_path)

        # 生成图片文件名
        new_filename = '{}_{}'.format(datetime.now().strftime('%Y%m%d%H%M%S%f'), file.name)
        file_path = os.path.join(folder_path, new_filename)

        # 保存图片
        with open(file_path, 'wb+') as destination:
            for chunk in file.chunks():
                destination.write(chunk)

        # 返回图片URL
        image_url = '{}{}/{}'.format(settings.MEDIA_URL, datetime.now().strftime('%Y/%m/%d'), new_filename)
        return JsonResponse({"code": 200, "file_name": file.name, "url": img_address + image_url,
                             'image_url': local_ip + image_url,
                             "message": "图片上传成功"})
    else:
        return JsonResponse({
            "code": 100,
            "message": "图片上传失败"
        })
